<?php
/**
 * 后台数据管理相关操作
 * 作者：刘单风
 * 最后修改时间：2016-12-23
 * 版权：刘单风个人所有
 */
namespace app\admin\controller;
use app\model\Luckprizes;
use app\model\Lucksponsor;
use MoCommon\DataState\SponsorTypeCodes;
use MoCommon\DataState\TeamNumCodes;
use MoCommon\Services\UploadFiles;
use think\Controller;
use think\Hook;
use think\facade\Env;
use think\facade\Config;
use OSS\OssClient;
use OSS\Core\OssException;

class Admin extends Controller
{
    public function _initialize()
    {
        parent::_initialize();
        Hook::listen('CheckAuth');
    }

    /**
     * 赞助商列表数据
     */
    public function Sponsorlist()
    {
        $sponsorModel = new Lucksponsor();
        $sponsor=$sponsorModel->dataList();
        $this->assign('sponsors', $sponsor);
        return $this->fetch('sponsors');
    }

    /**
     * 添加/编辑赞助商
     * @param int $id 赞助商id
     */
    public function addSponsor($id = 0)
    {
        $sponsorModel = new Lucksponsor();
        if ($id) {
            $sponsor = $sponsorModel->oneDetail(["id" => $id]);
        } else {
            $sponsor = $sponsorModel->Lucksponsor();
        }
        //赞助商跳转类型
        $jumptype = SponsorTypeCodes::$val;
        $this->assign("jumptypearr", $jumptype);
        $this->assign("sponsor", $sponsor);
        return $this->fetch('addsponsor');
    }

    /**
     * 赞助商保存
     */
    public function doAddSponsor()
    {
        $sponsorModel = new Lucksponsor();
        //查询是否存在
        $where = [
            'sp_name' => $_POST['spname']
        ];
        if ($_POST['id']) {
            $where['id'] = "!=" . $_POST['id'];
        }
        $data = $sponsorModel->oneDetail($where);
        if ($data) {
            $this->error('该赞助商已经存在，请重新输入', '/sponsor/add');
        } else {
            $insrtdata = [
                'sp_name' => $_POST['spname'],
                'sp_img' => trim($_POST['spimg'],";"),
                'jump_url' => $_POST['jumpurl'],
                'sp_contact' => $_POST['spcontact'],
                'jump_type' => $_POST['jumptype'],
                'sp_info' => $_POST['spinfo'],
                'audit_status' => $_POST['auditstatus']?:0,
                'link_name' => $_POST['linkname'],
                'user_id' => 0
            ];
            if ($_POST['id']) {
                $sponsorModel->updateOne($insrtdata, ['id' => $_POST['id']]);
            } else {
                $sponsorModel->addOne($insrtdata);
            }
            $this->success('保存成功', '/sponsor/list');
        }
    }


    //删除赞助商logo图
    public function delSponsorimg()
    {
        $id = $_POST['id'];
        $imgurl = $_POST['imgurl'];
        $img = explode("luckprizeimgs", $imgurl);
        $this->delPic($img[1]);
        $sponsorModel = new Lucksponsor();
        $sponsorModel->updateOne(['sp_img' => ""], ['id' => $id]);
        echo 0;
        exit;
    }

    /**
     * 审核赞助商
     * @param $id 赞助商id
     * @param $type 审核类型1通过;2不通过
     */
    public function auditSponsor($id,$type)
    {
        $sponsorModel = new Lucksponsor();
        $sponsorModel->updateOne(['audit_status' => $type], ['id' => $id]);
        echo "<script>alert('操作成功');window.location.href='/sponsor/list';</script>";
    }

    /**
     * 奖品列表
     */
    public function Prizelist()
    {
        $keywords = input("keywords", "");
        $prizesource = input("prizesource", 0);
        $prizeisopen = input("prizeisopen", 0);
        $where = [];
        if ($prizesource != -1) {
            if (empty($prizesource)) {
                $where['sponsor_id'] = 0;//个人
            } else {
                $where ['user_id'] = 0;//公司
            }
        }
        if ($prizeisopen != -1) {
            $where['is_open'] = $prizeisopen;
        }
        $luckprizeModel = new Luckprizes();
        $prizelist = $luckprizeModel->dataList($where, $keywords);
        $this->assign("prizelist", $prizelist);
        $this->assign("keywords", $keywords);
        $this->assign("prizesource", $prizesource);
        $this->assign("prizeisopen", $prizeisopen);
        return $this->fetch('luckprizes');
    }


    /**
     * 添加奖品
     * @param int $id
     */
    public function addPrize($id=0)
    {
        $sponsorModel = new Lucksponsor();
        $luckprizeModel = new Luckprizes();
        if ($id) {
            $prize = $luckprizeModel->oneDetail(["id" => $id]);
        } else {
            $prize = $luckprizeModel->Luckprizes();
        }
        //组队人数选项
        $teamnum = TeamNumCodes::$val;
        $this->assign("teamnumarr", $teamnum);
        //获取赞助商列表数据
        $sponsors = $sponsorModel->dataList(['audit_status' => 1]);
        $this->assign("sponsors", $sponsors);
        $this->assign("luckprize", $prize);
        return $this->fetch('addprize');
    }

    /**
     * 保存奖品信息
     */
    public function doAddPrize()
    {
        $luckprizeModel = new Luckprizes();
        //查询是否存在
        $where = [
            'prize_title' => $_POST['prizetitle'],
            'sponsor_id' => $_POST['sponsorid']
        ];
        if ($_POST['id']) {
            $where['id'] = "!=" . $_POST['id'];
        }
        $data = $luckprizeModel->oneDetail($where);
        if ($data) {
            $this->error('该抽奖已经存在，请重新输入', '/prize/add');
        } else {
            $insrtdata = [
                'prize_title' => $_POST['prizetitle'],
                'prize_img' => trim($_POST['prizeimg'], ";"),
                'open_time' => $_POST['fullnum'] ? 0 : strtotime($_POST['opentime']),
                'full_num' => $_POST['fullnum'] ?: 0,
                'sponsor_id' => $_POST['sponsorid'] ?: 0,
                'prize_msg' => $_POST['prizemsg'],
                'prize_num' => $_POST['prizenum'],
                'publish_time' => $_POST['publishtime']?(strtotime($_POST['publishtime'])):strtotime(date('Y-m-d H:i')),
                'prize_type' => $_POST['jointype'],
                'sort_num' => $_POST['sortnum'],
                'user_id' => 0,
                'is_logicdel' => 0
            ];
            if ($_POST['id']) {
                $data = $luckprizeModel->oneDetail(['id' => $_POST['id']]);
                //查看之前是否有奖品封面图
                if ($data['prize_img'] && $insrtdata['prize_img'] != $data['prize_img']) {
                    //说明是更新封面图,删除之前的封面图
                    $img = explode("luckprizeimgs", $data['prize_img']);
                    $this->delPic($img[1]);
                }
                $luckprizeModel->updateOne($insrtdata, ['id' => $_POST['id']]);
                $prizeid = $_POST['id'];
            } else {
                $insrtdata['create_time'] = strtotime(date('Y-m-d H:i'));
                $insrtdata['is_open'] = 0;
                $prizeid = $luckprizeModel->addOne($insrtdata);
            }
            $this->success('保存成功', '/prize/list');
        }
    }

    /**
     * 删除奖品
     * @param $id
     */
    public function delPrize($id)
    {
        $luckprizeModel = new Luckprizes();
        $luckprizeModel->updateOne(['is_logicdel' => 1], ['id' => $id]);
        $this->success('删除成功', '/prize/list');
    }

    /**
     * 中奖者列表
     * @param $id
     */
    public function Prizewinners($id)
    {
        $luckprizeModel = new Luckprizes();
        $winners=$luckprizeModel->winnerlist($id);
        $this->assign("winners", $winners['winners']);
        $this->assign("prizetitle", $winners['prizetitle']);
        $this->assign("prizetype", $winners['prizetype']);
        $this->assign("id", $id);
        return $this->fetch('winners');

    }

    /**
     *处理Excel导出
      *@param $datas array 设置表格数据
      *@param $titlename string 设置head
      *@param $title string 设置表头
    */
    public function Winnerexport($id)
    {
        $luckprizeModel = new Luckprizes();
        $winners=$luckprizeModel->winnerlist($id);
        //设置表头：
        $head = ['用户ID', '用户昵称', '收货人', '联系电话','所在地区', '详细地址'];
        //数据中对应的字段，用于读取相应数据：
        $keys = ['id', 'nick_name', 'consignee', 'link_phone', 'link_area','link_address'];
        foreach ($winners['winners'] as $item){
            $winnerdata[]=array(
                'id'=>$item['user_id'],
                'nick_name'=>$item['nick_name'],
                'consignee'=>$item['addr']['consignee'],
                'link_phone'=>$item['addr']['link_phone'],
                'link_area'=>$item['addr']['link_area'],
                'link_address'=>$item['addr']['link_address'],
            );
        }
        //获取奖品名称
        $luckprizeModel->dataexport($winners['prizetitle'].'-中奖者名单', $winnerdata, $head, $keys);
    }

    //奖品列表excel导出
    public function Prizeexport()
    {
        $keywords = input("keywords", "");
        $prizesource = input("prizesource", 0);
        $prizeisopen = input("prizeisopen", 0);
        $where = [];
        if ($prizesource != -1) {
            if (empty($prizesource)) {
                $where['sponsor_id'] = 0;//个人
            } else {
                $where ['user_id'] = 0;//公司
            }
        }
        if ($prizeisopen != -1) {
            $where['is_open'] = $prizeisopen;
        }
        $luckprizeModel = new Luckprizes();
        $prizelist = $luckprizeModel->dataList($where, $keywords,1);
        //设置表头：
        $head = ['奖品ID', '奖品名称', '赞助商', '创建时间','开奖时间', '开奖方式','奖品类型','奖品数量','参与人数','是否开奖'];
        //数据中对应的字段，用于读取相应数据：
        $keys = ['id', 'prize_title', 'sp_name', 'create_time', 'open_time','full_num','prize_type','prize_num','join_num','is_open'];
        //获取奖品名称
        $luckprizeModel->dataexport('医有礼抽奖统计-'.date('Y.m.d'), $prizelist, $head, $keys);
    }

    //上传文件
    public function uploadFiles()
    {
        $imgfiletype = input('imgfiletype');
        if ($imgfiletype) {
            $file = $_FILES['logofile'];
        }else{
            $file = $_FILES['file'];
        }
        //将文件上传到本地
        $picname = UploadFiles::singlefileupload('', $file, Env::get('ROOT_PATH') . 'public/temp/', '');
        $alioss = Config::get('app.alioss');
        $accessKeyId = $alioss['accesskey'];
        $accessKeySecret = $alioss['accesskeysecret'];
        $endpoint = $alioss['endpoint'];
        // 存储空间名称
        $bucket = $alioss['bucket'];
        // 文件名称
        $object = "luckprizeimgs/$picname";
        $filePath = Env::get('ROOT_PATH') . 'public/temp/' . $picname;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->uploadFile($bucket, $object, $filePath);
        } catch (OssException $e) {
            //文件上传失败
        } finally {
            //删除服务器上的临时文件
            unlink($filePath);
        }

        $prizeimg = "https://medi-community.oss-cn-beijing.aliyuncs.com/" . $object;
        if ($imgfiletype) {
            echo "<p style='color:red'>上传成功！</p>";
            echo "<script>window.parent.document.getElementById('prizeimg').value='" . $prizeimg . "';</script>";
        } else {
            echo $prizeimg;
        }
        exit();
    }

    //阿里云删除图片
    public function delPic($imgname)
    {
        $alioss = Config::get('app.alioss');
        $accessKeyId = $alioss['accesskey'];
        $accessKeySecret = $alioss['accesskeysecret'];
        $endpoint = $alioss['endpoint'];
        // 存储空间名称
        $bucket = $alioss['bucket'];
        // 文件名称
        $object = "luckprizeimgs" . $imgname;
        try {
            $ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
            $ossClient->deleteObject($bucket, $object);
        } catch (OssException $e) {
            //文件删除失败
        }
    }


}
